var mongoose = require('../../../../../framework/mongoose');
var service = require('./service');

var CmsVideo = require('./model').CmsVideo;

//Rest Interface
exports.queryVideoBySubId = function (req, res) {
    CmsVideo.find({subscription: req.query.subId}).sort('order').exec(function (err, videos) {
        res.send({code: 1, data: {videos: videos}});
    });
};
exports.findById = function(req, res){
    mongoose.findById(Video, req.params.id, function(obj) {res.send({video: obj});});
};

exports.save = function (req, res) {
    var url =  req.body.url;
    var youkuId = url.substring(url.lastIndexOf('id_') + 3, url.lastIndexOf('.html')); // v_show/id_XNTc2NDczNzcy.html

    var cmsVideo = new CmsVideo({
        title: req.body.title,
        descr: req.body.descr,
        url: url,
        playUrl: 'http://player.youku.com/embed/' + youkuId,
        createDate: new Date(),
        subscription: req.body.subId
    });
    cmsVideo.save(function(){
        return res.send({code: 1});
    });
};

exports.update = function(req, res){
    var url =  req.body.url;
    var youkuId = url.substring(url.lastIndexOf('id_') + 3, url.lastIndexOf('.html')); // v_show/id_XNTc2NDczNzcy.html

    CmsVideo.findByIdAndUpdate(
        req.params.id,
        {
            title: req.body.title,
            descr: req.body.descr,
            url: url,
            playUrl: 'http://player.youku.com/embed/' + youkuId,
            updateDate: new Date()
        }, function(){
            return res.send({code: 1});
        }
    )
};

exports.delete = function(req, res){
    CmsVideo.findByIdAndRemove(req.params.id, function(){
        return res.send({code: 1});
    })
};